<?php

namespace app\api\middleware;


use app\common\Result;
use joncc\attribute\Attribute;
use \joncc\attribute\attr\Params as AParams;
use think\Request;

class Params
{

    public function handle(Request $request, \Closure $next)
    {
        [$module, $controller, $action] = get_mca();
        $className = 'app\\' . $module . '\controller\\' . $controller;

        $instance = Attribute::instance()->make($className);
        $methodParams = $instance->methodParamsList($action);

        $params = $request->param();
        $p = [];
        foreach ($methodParams as $param) {
            if (!isset($params[$param['name']])) {
                continue;
            }

            $v = $params[$param['name']];
            if ($param['required'] && empty($v) && 0 != $v) {
                Result::httpException($param['name'] . '字段必填!');
            }

            switch ($param['type']) {
                case AParams::INT:
                    $p[$param['name']] = (int)$v;
                    break;
                case AParams::BOOL:
                    $v = (int)$v;
                    if (!in_array($v, [0, 1])) {
                        Result::httpException($param['name'] . '字段必须为0或1!');
                    }
                    $p[$param['name']] = $v;
                    break;
                case AParams::JSON:
                    $p[$param['name']] = json_decode($v, true);
                    break;
                case AParams::ARRAY:
                    if (is_string($v)) {
                        $v = explode(',', $v);
                    }
                    $p[$param['name']] = (array)$v;
                    break;
                case AParams::STRING:
                    $p[$param['name']] = (string)$v;
                    break;
            }
        }

        $request->bizParams = $p;
        return $next($request);
    }
}